package com.atguigu.gmall.common.service;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author atguigu-mqx
 */
@Service
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //  编写发送消息的方法.
    public boolean sendMsg(String exchange , String routingKey , Object msg){
        //  发送消息
        this.rabbitTemplate.convertAndSend(exchange,routingKey,msg);
        return true;
    }

    /**
     *  编写发送延迟消息的方法.
     * @param exchange
     * @param routingKey
     * @param msg
     * @param delayTime 延迟时间 默认毫秒，变成秒
     * @return
     */
    public boolean sendDelayMsg(String exchange , String routingKey , Object msg,int delayTime){
        /*
       this.rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay,DelayedMqConfig.routing_delay,"ok---",(message)->{
            //  利用消息对象设置延迟时间
            message.getMessageProperties().setDelay(10000);
            System.out.println(simpleDateFormat.format(new Date())+":\t sendMsg");
            return message;
        });
         */
        //  发送消息
        this.rabbitTemplate.convertAndSend(exchange,routingKey,msg,(message)-> {
            message.getMessageProperties().setDelay(delayTime*1000);
            return message;
        });
        return true;
    }
}
